package com.central.scheduler.plugin.registry.zookeeper;

import com.central.scheduler.spi.register.RegistryConnectListener;
import com.central.scheduler.spi.register.RegistryConnectState;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Tindy
 * @date 2021/10/29
 * @describe
 */
public class ZookeeperConnectionStateListener implements ConnectionStateListener {

    private static final Logger logger = LoggerFactory.getLogger(ZookeeperConnectionStateListener.class);

    private RegistryConnectListener registryConnectListener;

    public ZookeeperConnectionStateListener(RegistryConnectListener registryConnectListener) {
        this.registryConnectListener = registryConnectListener;
    }

    @Override
    public void stateChanged(CuratorFramework client, ConnectionState newState) {

        if (newState == ConnectionState.LOST) {
            logger.error("connection lost from zookeeper");
            registryConnectListener.notify(RegistryConnectState.LOST);
        } else if (newState == ConnectionState.RECONNECTED) {
            logger.info("reconnected to zookeeper");
            registryConnectListener.notify(RegistryConnectState.RECONNECTED);
        } else if (newState == ConnectionState.SUSPENDED) {
            logger.warn("zookeeper connection SUSPENDED");
            registryConnectListener.notify(RegistryConnectState.SUSPENDED);
        }

    }

}
